﻿using System;
using System.Collections.Generic;
using UnityEngine;

public class GameEvent
{

}
public class CreatSoldierEvent : GameEvent
{

}
public class AddCoinEvent : GameEvent
{
    public  int number;
    public AddCoinEvent(int n)
    {
        number = n;
    }
}

public class GameOverEvent : GameEvent
{
    
}

public class EventManager
{
    #region 单例
    private static EventManager instance = null;
    public static EventManager Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new EventManager();
            }

            return instance;
        }
    }
    private EventManager() { }
    #endregion

    public delegate void EventDelegate<T>(T e) where T : GameEvent;
    private Dictionary<Type, Delegate> delegates = new Dictionary<Type, Delegate>();

    /// <summary>
    /// 添加事件响应
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="del"></param>
    public void AddListener<T>(EventDelegate<T> del) where T : GameEvent
    {
        if (delegates.ContainsKey(typeof(T)))
        {
            Delegate tempDel = delegates[typeof(T)];

            delegates[typeof(T)] = System.Delegate.Combine(tempDel, del);
        }
        else
        {
            delegates[typeof(T)] = del;
        }
    }

    /// <summary>
    /// 移除事件
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="del"></param>
    public void RemoveListener<T>(EventDelegate<T> del) where T : GameEvent
    {
        if (delegates.ContainsKey(typeof(T)))
        {
            var currentDel = System.Delegate.Remove(delegates[typeof(T)], del);

            if (currentDel == null)
            {
                delegates.Remove(typeof(T));
            }
            else
            {
                delegates[typeof(T)] = currentDel;
            }
        }
    }

    /// <summary>
    /// 激活事件
    /// </summary>
    /// <typeparam name="T">事件类型</typeparam>
    /// <param name="e">事件</param>
    public void Raise<T>(T e) where T : GameEvent
    {
        if (e == null)
        {
            Debug.Log("Invalid event argument: " + e.GetType().ToString());
            return;
        }

        //if (delegates.ContainsKey(e.GetType()))
        //{
        //    delegates[e.GetType()].DynamicInvoke(e);
        //}
        foreach (EventDelegate<T> del in delegates[e.GetType()].GetInvocationList())
        {
            del.Invoke(e);
        }
    }
}